package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.House;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author lhh
 * @ClassName HouseImageController
 * @date 2022/9/19 18:49
 */
@Controller
@RequestMapping("houseImage")
public class HouseImageController {

    @Reference
    private HouseImageService houseImageService;

    @GetMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable Long houseId , @PathVariable Long type, Model model){

        model.addAttribute("houseId",houseId);
        model.addAttribute("type",type);
        return "house/upload";
    }

    @PostMapping("upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId ,
                       @PathVariable Integer type,
                       @RequestParam(value = "file") MultipartFile[] filters) throws IOException {
        if(filters.length>0){
            for (MultipartFile filter : filters) {
                String newFileName=UUID.randomUUID().toString();
                String imageName=newFileName+filter.getOriginalFilename();
                QiniuUtil.upload2Qiniu(filter.getBytes(),imageName);
                String url="http://rigc48hkx.hb-bkt.clouddn.com/"+imageName;
                System.out.println("url = " + url);
                HouseImage houseImage = new HouseImage();
                houseImage.setHouseId(houseId);
                houseImage.setImageUrl(url);
                houseImage.setImageName(imageName);
                houseImage.setType(type);
                houseImageService.save(houseImage);
            }
        }
        return Result.ok();
    }

   @GetMapping("delete/{houseId}/{id}")
    public String remove(@PathVariable Long houseId,@PathVariable Long id){
       HouseImage houseImage = houseImageService.getById(id);
       houseImageService.remove(houseImage.getImageName());
       QiniuUtil.deleteFileFromQiniu(houseImage.getImageName());
       return "redirect:/house/"+houseId;
   }
}
